<template>
  <el-dialog
    :visible.sync="visible"
    :title="!dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="80px"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmitHandle()"
      :label-width="$i18n.locale === 'en-US' ? '120px' : '120px'"
    >
      <el-row :gutter="30">
        <el-col :span="24">
          <el-form-item label="旅行路线名称" prop="name">
            <el-input
              v-model="dataForm.name"
              placeholder="旅行路线名称"
            ></el-input>
          </el-form-item>
        </el-col>
         <el-col :span="24">
          <el-form-item label="排序" prop="sortVal">
            <el-input
              v-model="dataForm.sortVal"
              placeholder="排序"
              type="number"
              min="0"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="跳转导览图" prop="skipListName">
            <el-select
              value-key="id"
              v-model="dataForm.skipListName"
              placeholder="请选择"
              multiple
            >
              <el-option
                v-for="(item, index) in skipList"
                :key="index"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <p class="pdl60">
            推荐详情图<span>(支持png、jpg，建议尺寸750*1332px，最多1张)</span>
          </p>
        </el-col>
        <el-col :span="24">
          <el-form-item label="" prop="coverImage">
            <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="true"
              :multiple="false"
              :limit="1"
              :on-success="(res, file, fileList) => successHandle1(res)"
              :before-upload="(file) => beforeUploadHandle(file, 'coverImage')"
            >
              <img
                v-if="dataForm.detailImage"
                :src="dataForm.detailImage"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <p class="pdl60">
            路线详情缩略图<span
              >(支持png、jpg，建议尺寸750*320px，最多5张)</span
            >
          </p>
        </el-col>
        <el-col :span="24">
          <el-form-item label="" prop="">
            <el-upload
              :action="url"
              :file-list="fileList"
              :limit="5"
              :before-upload="
                (file) => beforeUploadHandle(file, 'coverImageList')
              "
              list-type="picture-card"
              :on-success="successHandle"
              :on-remove="handleRemove"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            :label="`${'第' + (index + 1) + '天'}`"
            v-for="(items, index) in dataForm.scheduleList"
            :key="index"
            :prop="'scheduleList.' + index + '.scenicSpotIdArr'"
            :rules="{
              required: true,
              message: '请输入',
              trigger: 'blur',
            }"
            style="background: #f7f7f7; padding: 15px 0; margin-bottom: 10px"
          >
            <div v-for="(item2, index2) in items.scenicSpotList" :key="index2">
              <el-col
                :span="24"
                style="margin-bottom: 10px; position: relative"
              >
                <el-form-item label="景点" prop="spotId">
                  <el-select
                    value-key="id"
                    v-model="item2.spotId"
                    placeholder="请选择名称"
                  >
                    <el-option
                      v-for="(item, index) in SpotList"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                  <el-input
                    type="hidden"
                    :value="item2.spotId | delSpot(index, index2)"
                    class="hiddenInput"
                  ></el-input>
                  <el-button
                    type="danger"
                    size="mini"
                    @click="deletdata(item2, index2, index)"
                    style="
                      margin-left: 15px;
                      margin-top: 10px;
                      transform: scale(0.8);
                    "
                    >删除景点</el-button
                  >
                  <el-button
                    type="primary"
                    size="mini"
                    @click="adddata(item2, index2, index)"
                    v-if="index2 == items.scenicSpotList.length - 1"
                    style="
                      margin-top: 10px;
                      margin-left: 0px;
                      transform: scale(0.8);
                    "
                    >添加景点</el-button
                  >
                </el-form-item>
              </el-col>
            </div>

            <el-col :span="18" style="margin-bottom: 20px">
              <el-form-item label="住宿">
                <el-select
                  value-key="id"
                  v-model="items.hotelIdArr"
                  placeholder="请选择名称"
                  multiple
                  collapse-tags
                  style="width:100%"
                >
                  <el-option
                    v-for="(item, index) in zhusulist"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" style="margin-bottom: 10px">
              <el-form-item label="推荐游览理由" prop="recommendReason">
                <el-input
                type="textarea"
                rows="4"
                  v-model="items.recommendReason"
                  placeholder="推荐游览理由"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-button
              type="danger"
              size="mini"
              @click="deleteDays(index)"
              style="transform: scale(0.8); margin-left: 0"
              >删除天数</el-button
            >
            <el-button
              type="primary"
              size="mini"
              v-if="index == dataForm.scheduleList.length - 1"
              @click="addDays()"
              style="transform: scale(0.8); margin-left: 0"
              >添加天数</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item> </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
    <!-- 裁剪框 -->
    <cropper-dlg
      v-if="showCropper"
      :dialogVisible.sync="showCropper"
      :img-file="currentFile"
      ref="vueCropper"
      @upload="cropperUpload"
    ></cropper-dlg>
  </el-dialog>
</template>

<script>
var that;
import Cookies from "js-cookie";
import debounce from "lodash/debounce";
export default {
  data() {
    return {
      currentFile: "",
      cropperIndex: null,
      showCropper: false, //裁剪弹框
      isCropper: true, //上传之前是否显示裁剪
      SpotList: [],
      zhusulist: [],
      scheduleList: [],
      visible: false,
      tagOptions: [],
      islandOptionList: [],
      url: `${
        window.SITE_CONFIG["apiURL"]
      }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
      // url: `https://i.ringzle.com/island-cloud-server/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
      fileList: [],
      skipList: [
        {
          name: "泗礁岛",
          skipGuideVal: "泗礁岛",
          picImage:
            "https://i.ringzle.com/file/20240419/d8820963e77f4a16bd1367d62609dec6.png",
        },
        {
          name: "枸杞岛",
          skipGuideVal: "枸杞岛、嵊山岛",
          picImage:
            "https://i.ringzle.com/file/20240419/0d6acb373cc34117b6f711a3a0acf188.png",
        },
        {
          name: "花鸟岛",
          skipGuideVal: "花鸟岛",
          picImage:
            "https://i.ringzle.com/file/20240419/9b932cbd74e7455f8ccbf84f84d30f8a.png",
        },
        {
          name: "嵊山岛",
          skipGuideVal: "枸杞岛、嵊山岛",
          picImage:
            "https://i.ringzle.com/file/20240419/767800d23d7c40ecb62d7c4c57564f8b.png",
        },
        {
          name: "黄龙岛",
          skipGuideVal: "黄龙岛",
          picImage:
            "https://i.ringzle.com/file/20240419/2278390803574397af88a43fde5f64d5.png",
        },
        {
          name: "洋山岛",
          skipGuideVal: "大、小洋山岛",
          picImage:
            "https://i.ringzle.com/file/20240419/5494eed457fd48acb5d1af85cafd6b5d.png",
        },
      ],
      dataForm: {
        id: "",
        name: "",
        intro: "",
        detailImage: "",
        coverImageList: [],
        skipList: [],
        skipListName: [],
        sortVal:'',
        scheduleList: [
          {
            recommendReason: "",
            scenicSpotList: [
              {
                spotId: "",
                sourceType: "",
              },
            ], //景点
            hotelIdArr: [], //住宿
          },
        ],
      },
    };
  },
  mounted() {
    this.getScenicSpot();
    this.getzhusu();
    that = this;
  },
  watch: {
    "dataForm.scheduleList": {
      deep: true,
      handler(newV) {},
    },
  },
  filters: {
    delSpot(val, index, index2) {
      let typeBoj = that.SpotList.filter((item) => item.id == val);
      if (typeBoj[0]) {
        that.dataForm.scheduleList[index].scenicSpotList[index2].sourceType =
          typeBoj[0].type;
      }
    },
  },
  computed: {
    dataRule() {
      return {
        name: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        intro: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        planDayNum: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        planPlaceNum: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        creator: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        createDate: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        updater: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        updateDate: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  methods: {
    // 上传成功
    successHandle1(res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      this.dataForm.detailImage = res.data.url;
    },

    adddata(e, i, i2) {
      this.dataForm.scheduleList[i2].scenicSpotList.push({
        spotId: "",
        sourceType: "",
      });
    },
    deletdata(e, i, i2) {
      this.dataForm.scheduleList[i2].scenicSpotList.splice(i, 1);
    },

    handleRemove(file, fileList) {
      // this.dataForm.coverImageList = fileList.map((item) => {
      //   return item.url;
      // });
      // const removeIndex = this.fileList.findIndex((i) => i.url == file.url);
      // this.fileList.splice(removeIndex, 1);
      this.fileList = fileList.map((item) => {
        return item;
      });
    },
    // 上传之前
    beforeUploadHandle(file, name) {
      if (
        file.type !== "image/jpg" &&
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$message.error(
          this.$t("upload.tip", {
            format: "jpg、png、gif",
          })
        );
        return false;
      }
      if (this.isCropper) {
        //显示裁剪
        this.currentFile = file;
        this.cropperIndex = name;
        this.showCropper = true;
        this.$nextTick(() => {
          this.$refs.vueCropper.init();
        });
        return false;
      }
    },

    cropperUpload(data) {
      this.showCropper = false;
      if (data != "close") {
        //裁剪成功后获取的图片
        this.$http.post("/oss/file/aliyunUpload", data).then((res) => {
          if (res.data.code == 0) {
            if (this.cropperIndex == "coverImageList") {
              //多张
              this.successHandle(res.data);
            } else {
              //一张
              this.successHandle1(res.data, this.cropperIndex);
            }
          }
        });
      }
    },
    // 上传成功
    successHandle(res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      this.fileList.push({
        name: "",
        url: res.data.url,
      });
    },

    //获取景点list
    getScenicSpot() {
      this.$http
        .get("/sys/ismap/selectCusSpotPage", {
          params: {
            homestayId: "",
            page: 1,
            limit: 99,
            area: "",
            scenicId: "",
            type: "other",
          },
        })
        .then((res) => {
          this.SpotList = res.data.data.list;
        });
    },
    //获取住宿list
    getzhusu() {
      this.$http
        .get("/sys/ismap/selectCusSpotPage", {
          params: {
            homestayId: "",
            page: 1,
            limit: 99,
            area: "",
            scenicId: "",
            type: 2,
          },
        })
        .then((res) => {
          this.zhusulist = res.data.data.list;
          console.log("111111111111111111", this.zhusulist);
        });
    },
    deleteDays(index) {
      if (this.dataForm.scheduleList.length > 1) {
        this.dataForm.scheduleList.splice(index, 1);
      }
    },
    addDays() {
      this.dataForm.scheduleList.push({
        recommendReason: "",
        scenicSpotList: [
          {
            spotId: "",
            sourceType: "",
          },
        ], //景点
        hotelIdArr: [], //住宿
      });
    },
    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.fileList = [];
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.getInfo();
          return;
        }
        this.scheduleList = [{ scenicSpotIdArr: [] }];
        this.dataForm = {
          id: "",
          name: "",
          intro: "",
          detailImage: "",
          coverImageList: [],
          scheduleList: [
            {
              recommendReason: "",
              scenicSpotList: [
                {
                  sourceType: "",
                  spotId: "",
                },
              ], //景点
              hotelIdArr: [], //住宿
            },
          ],
        };
      });
    },
    // 获取信息
    getInfo() {
      this.$http
        .get(`/scenic/travelguideroute/${this.dataForm.id}`)
        .then(({ data: res }) => {
          this.fileList = [];
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
          if (this.dataForm.skipList) {
            this.dataForm.skipListName = this.dataForm.skipList.map((item) => {
              return item.name;
            });
          }
          this.scheduleList = this.dataForm.scheduleList;
          this.dataForm.coverImageList.filter((item) => {
            this.fileList.push({
              url: item,
            });
          });
        })
        .catch(() => {});
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        // this.$refs['dataForm'].validate((valid) => {
        //     if (!valid) {
        //         return false
        //     }
        // 处理跳转导览图
        this.dataForm.skipList = [];
        this.skipList.filter((item) => {
          if (this.dataForm.skipListName.indexOf(item.name) > -1) {
            this.dataForm.skipList.push(item);
          }
        });
        this.dataForm.coverImageList = this.fileList.map((item) => {
          return item.url;
        });
        this.$http[!this.dataForm.id ? "post" : "put"](
          "/scenic/travelguideroute/",
          this.dataForm
        )
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg);
            }
            this.$message({
              message: this.$t("prompt.success"),
              type: "success",
              duration: 500,
              onClose: () => {
                this.visible = false;
                this.$emit("refreshDataList");
              },
            });
          })
          .catch(() => {});
        //  })
      },
      1000,
      {
        leading: true,
        trailing: false,
      }
    ),
  },
};
</script>

<style scoped lang="scss">
.avatar-uploader {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    .el-upload:hover {
      border-color: #409eff;
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 158px;
    height: 158px;
    line-height: 158px;
    text-align: center;
  }

  .avatar {
    width: 158px;
    height: 158px;
    display: block;
  }
}
.hiddenInput {
  position: absolute;
  top: 0;
}
</style>
